package com.myqf2.d10_dbutils_xml.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * DOM解析
 * Document Object MODEL
 */
public class Demo {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        //1.创建一个Document解析工厂
        DocumentBuilderFactory dbf=
                DocumentBuilderFactory.newInstance();

        //2.从解析工厂中得到解析器
        DocumentBuilder db
                = dbf.newDocumentBuilder();
        //3.通过解析器，解析文档成为一个Document对象
        Document dom = db.parse("/Users/liuzhuangzhuang/IdeaProjects/qfs2s-demo/src/main/java/com/myqf2/d10_dbutils_xml/xml/book.xml");
        //4.解析Document对象，遍历节点
        NodeList books = dom.getElementsByTagName("book");
        //遍历所有的book集合
        for(int i=0;i<books.getLength();i++){
            //将每一个节点强转为一个element
            Element element = (Element) books.item(i);
            String title = element.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
            System.out.println(title);

            String author = element.getElementsByTagName("author").item(0).getFirstChild().getNodeValue();
            System.out.println(author);
            System.out.println("====================================");
        }


    }
}
